package com.wosai.register.security;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.http.HttpStatus;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.AuthenticationEntryPoint;
import org.springframework.web.client.HttpClientErrorException;

public class RestAuthenticationEntryPoint implements AuthenticationEntryPoint {
    private static final Log logger = LogFactory.getLog(RestAuthenticationEntryPoint.class);

    @Override
    public void commence(HttpServletRequest request,
                         HttpServletResponse response,
                         AuthenticationException authException)
                                 throws IOException,
                                 ServletException
    {
//        response.sendError( HttpServletResponse.SC_UNAUTHORIZED, "Unauthorized: Authentication token was either missing or invalid." );
//        throw new HttpClientErrorException(HttpStatus.UNAUTHORIZED, "Unauthorized: Authentication token was either missing or invalid.");
        
        String error = "Unauthorized: Authentication token was either missing or invalid.";
        response.setStatus(HttpServletResponse.SC_UNAUTHORIZED,  error);
        ServletOutputStream os = response.getOutputStream();
        byte[] output = String.format("{\"message\": \"%s\" }\n", error).getBytes(); 
        os.write(output);
        os.close();

    }

}
